<script setup lang="ts">
import type { StudentWordItem } from '@/api/types/student'
import NavBar from '@/components/NavBar/index.vue'
import ReviewWordCard from '@/components/WordCard/ReviewWordCard.vue'
import { useStudyWords } from '@/composables/useStudyWords'
import { handleNextStep, LearningState } from '@/services/learningStateMachine'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { onMounted } from 'vue'
import '@/scss/wordMemory.scss'

const unitStudyWordsStore = useUnitStudyWordsStore()
const {
  localWords,
  activeWordId,
  initStudyWords,
  updateWordClickNum,
  randomizeWords,
  setActiveWord,
} = useStudyWords()

// 初始化本地数据
onMounted(() => {
  unitStudyWordsStore.updateStudyStartTime()
  initStudyWords(unitStudyWordsStore.currentGroup.words)
})

// 随机打乱单词顺序
function handleRandomWord() {
  randomizeWords()
}

// 下一个单词
function handleNextWord() {
  handleOnNext()
}

function handleWordActivate(wordId: string | number) {
  setActiveWord(wordId)
}

function handleCardClick(word: StudentWordItem) {
  updateWordClickNum(word.wordId)
}

// 单词识记完成后的下一步
function handleOnNext() {
  handleNextStep(LearningState.WORD_MEMORY)
}

function handleLeftClick() {
  uni.navigateBack()
}
</script>

<template>
  <view class="word-memory">
    <NavBar :title="`单词识记 第${unitStudyWordsStore.currentGroupIndex + 1}组`" @left-click="handleLeftClick" />

    <view class="word-container">
      <ReviewWordCard
        v-for="word in localWords"
        :key="word.wordId"
        :word="word"
        :is-active="activeWordId === word.wordId"
        class="word-card"
        @activate="handleWordActivate(word.wordId)"
        @click="handleCardClick(word)"
      />
    </view>

    <view class="footer">
      <view class="action-btn" @tap="handleRandomWord">
        <uni-icons type="refresh" size="24" color="#fff" />
        <text>随机</text>
      </view>
      <view class="action-btn primary" @tap="handleNextWord">
        <uni-icons type="arrow-right" size="24" color="#fff" />
        <text>下一步</text>
      </view>
    </view>
  </view>
</template>
